﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Controls.Maps;
using System.Device.Location;
using Microsoft.Phone.Tasks;
using unifiqAnthony.GeocodeService;
using System.Windows.Media;
using DeepForest.Phone.Assets.Tools;
using System.IO;
using System.Windows.Media.Imaging;
using System.Net;
using unifiqAnthony.UnifiqSvc;
using System.Text;

namespace unifiqAnthony
{
    public partial class ListingView : PhoneApplicationPage
    {
        internal const string id = "Aggp0yd8miqzaqQrXChtjs8v2m4nlHd3lFn06-W9gu7ZI4KBhTzUddWbVjayXfTV"; //Bing key
        List<byte[]> byteList;
        Listing listing;

        public ListingView()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
          
            // Populate Fields
            loadData();
        }

        void loadData()
        {
            var obj = App.Current as App;

            // Load Photos
            byteList = obj.byteList;

            int insCount = 1;
            foreach (byte[] x in byteList)
            {
                System.Diagnostics.Debug.WriteLine(x == null);

                if (x != null)
                {
                    Image img;
                    if (insCount == 1)
                    {
                        img = image1;
                        insCount++;
                    }
                    else if (insCount == 2)
                    {
                        img = image2;
                        insCount++;
                    }
                    else
                    {
                        img = image3;
                    }

                    BitmapImage bmp = new BitmapImage();
                    bmp.SetSource(new MemoryStream(x));

                    //bmp.SetSource(ms);
                    img.Source = bmp;
                }
            }
            

            // Get Listing Details
            UnifiqSvc.Listing l = obj.listing;
            this.listing = l;

            // Hide OwnerControl is Listing is not User's
            if (l.uid != obj.uid)
                OwnerControl.Visibility = Visibility.Collapsed;

            string msg = "";
            if (NavigationContext.QueryString.TryGetValue("msg", out msg))
                textBlock1.Text = msg;
            

            StringBuilder builder = new StringBuilder();

            builder.Append("Blk " + l.blkNo + " " + l.stName + " Road"  +"\n");
            builder.Append("#" + l.doorNo + "-" + l.apptNo + " " + l.bldngName +  "\n");
            builder.Append("S" + l.zipCode);
            tb_address.Text = builder.ToString();

            if (l.available == 'y')
            {   
                btn_taken.Content = "Mark as Taken";
            }
            else
            {
                btn_taken.Content = "Unmark as Taken";
                tb_avail.Visibility = Visibility.Visible;
            }

            tb_contactNo.Text = l.contactNo;
            tb_desc.Text = l.description;
            tb_fullName.Text = l.contactName;
            tb_noOfTenants.Text = l.noOfTenants.ToString();
            tb_fee.Text = "$" + l.fee.ToString();

            // Place Pushpin
            LoadAddressPushpin(l.lat,l.lon);
        }

        private void LoadAddressPushpin(double lat, double lon)
        {
            System.Diagnostics.Debug.WriteLine("Execute: " + lat + ", " + lon);
            Pushpin pin = new Pushpin();
            GeoCoordinate geo = new GeoCoordinate(lat, lon);

            Map.ZoomLevel = 17;
            Map.Center = geo;

            pin.Location = geo;
            pin.Template = this.Resources["listingPin"] as ControlTemplate;
            Map.Children.Add(pin);
        }

        void previewImage(int pos)
        {
            NavigationService.Navigate(new Uri("/ImagePreview.xaml?pos=" + pos, UriKind.Relative));
        }

        private void btn_image1_Click(object sender, RoutedEventArgs e)
        {
            if (image1.Source != null)
            {
                previewImage(1);
            }

        }

        private void btn_image2_Click(object sender, RoutedEventArgs e)
        {
            if (image2.Source != null)
            {
                previewImage(2);
            }
        }

        private void btn_image3_Click(object sender, RoutedEventArgs e)
        {
            //System.Diagnostics.Debug.WriteLine(image1.Source==null);

            if (image3.Source != null)
            {
                previewImage(3);
            }
        }

        private void btn_taken_Click(object sender, RoutedEventArgs e)
        {
            tb_loading.Text = "Updating";
            progressOverlay.Show();

            UnifiqSvc.ServiceSoapClient db = new UnifiqSvc.ServiceSoapClient();
            if (listing.available == 'y')
            {
                db.MarkAsTakenCompleted += new EventHandler<MarkAsTakenCompletedEventArgs>(db_MarkAsTakenCompleted);
                db.MarkAsTakenAsync(listing.listingId);
            }
            else
            {
                db.UnMarkAsTakenCompleted += new EventHandler<UnMarkAsTakenCompletedEventArgs>(db_UnMarkAsTakenCompleted);
                db.UnMarkAsTakenAsync(listing.listingId);
            }

        }
        void db_MarkAsTakenCompleted(object sender, UnifiqSvc.MarkAsTakenCompletedEventArgs e)
        {
            progressOverlay.Hide();
            if (e.Result == true)
            {
                tb_avail.Visibility = Visibility.Visible;
                NotificationTool.Show(
                "Marked as Taken",
                "You have marked this listing as Taken",
                new NotificationAction("OK", () => { }));

                listing.available = 'n';
                btn_taken.Content = "Unmark as Taken";
                tb_avail.Visibility = Visibility.Visible;
            }
            else
            {
                NotificationTool.Show(
                "Unable to Mark as Taken",
                "An error has occured",
                new NotificationAction("OK", () => { }));
            }
        }
        void db_UnMarkAsTakenCompleted(object sender, UnifiqSvc.UnMarkAsTakenCompletedEventArgs e)
        {
            progressOverlay.Hide();
            if (e.Result == true)
            {
                tb_avail.Visibility = Visibility.Visible;
                NotificationTool.Show(
                "Unmarked as Taken",
                "You have unmarked this listing as Taken",
                new NotificationAction("OK", () => {  }));

                listing.available = 'y';
                btn_taken.Content = "Mark as Taken";
                tb_avail.Visibility = Visibility.Collapsed;
            }
            else
            {
                NotificationTool.Show(
                "Unable to Unmark as Taken",
                "An error has occured",
                new NotificationAction("OK", () => {  }));

            }
        }

        private void btn_edit_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/ListingUpdate.xaml", UriKind.Relative));
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Back Button Pressed");

            var lastPage = NavigationService.BackStack.FirstOrDefault();

            if (lastPage != null && lastPage.Source.ToString() == "/ListingList.xaml")
            {
                e.Cancel = true; 

                NavigationService.RemoveBackEntry();
                NavigationService.Navigate(new Uri("/ListingList.xaml?back=" + "true", UriKind.Relative));
            }
            else
            {
                e.Cancel = false; 
            }

        }
    }
}